package org.xbzheng.restful_study.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.xbzheng.restful_study.model.Role;
import org.xbzheng.restful_study.model.User;
import org.xbzheng.restful_study.service.UserService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

@Component("userDetailsService")
public class UserSecurityService implements UserDetailsService {
    private static final Logger LOG = LoggerFactory.getLogger(UserSecurityService.class);
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.login(username);

        if(user == null){
            throw new UsernameNotFoundException("用户不存在！");
        }

        Collection<GrantedAuthority> authorities = new ArrayList<>();

        Set<Role> roles = user.getRoles();
        if(roles != null && !roles.isEmpty()){
            for(Role role : roles){
                SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getRoleStr());

                authorities.add(grantedAuthority);
                LOG.debug("User {} has the {} role.", username, role.getRoleStr());
            }
        }

        UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
        return userDetails;
    }
}
